/**
 *@描述：角色管理
 *@作者：顾云飞
 *@创建时间：2023/1/17
 *@最后修改时间：2023/1/18
 */
import {
  EllipsisOutlined,
  PlusOutlined,
  SearchOutlined,
  SyncOutlined,
  DeleteOutlined,
} from '@ant-design/icons';
import type { ActionType } from '@ant-design/pro-components';
import {
  Table,
  Space,
  Popconfirm,
  Button,
  message,
  Tag,
  Card,
  Pagination,
  PaginationProps,
  Form,
  Input,
} from 'antd';
import { queryRoleList, DeleteRoleRequest } from '@/pages/Dashboard/System/Role/service';
import { GetRoleListRequestParams } from './data';
import { useRef, useState, useEffect } from 'react';
import type { ColumnsType } from 'antd/es/table';

import RoleFormModal from './RoleFormModal';
import RolePermissionModal from './RolePermissonModal'; // 权限分配弹窗
interface RoleItem {
  id: string;
  isSys: string;
  name: string; // 真实姓名
  enname: string;
  rolePermission: string;
  sortNum: number;
  createDate: string;
  updateDate: string;
}

const RoleList = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [showRoleModal, setShowRoleModal] = useState<boolean>(false);
  const [roleFormValues, setRoleFormValues] = useState({});
  const [showRolePermissionModal, setShowRolePermissionModal] = useState<boolean>(false);
  const [roleId, setRoleId] = useState('');
  //组件初始化函数
  //todo: useEffect函数
  useEffect(() => {
    getRoleList({});
  }, []);

  const columns: ColumnsType<RoleItem> = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
      width: 160,
    },
    {
      title: '角色编码',
      dataIndex: 'enname',
      key: 'enname',
      width: 120,
    },
    {
      title: '是否系统数据',
      dataIndex: 'isSys',
      key: 'isSys',
      width: 120,
      render: (_, record) => (
        <Space>
          <Tag color={record.isSys === '1' ? '#67c23a' : '#00000040'} key={record.isSys}>
            {record.isSys === '1' ? '是' : '否'}
          </Tag>
        </Space>
      ),
    },
    //  {
    //    title: '排序',
    //    dataIndex: 'sortNum',
    //    key: 'sortNum',
    //    width:60
    //  },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      key: 'createDate',
      width: 160,
    },
    {
      title: '修改时间',
      dataIndex: 'updateDate',
      key: 'updateDate',
      width: 160,
    },
    {
      title: '操作',
      key: 'operation',
      width: 160,
      render: (_, record) => [
        <Button
          type="link"
          size="small"
          onClick={() => {
            setShowRolePermissionModal(true);
            setRoleId(record.id);
          }}
        >
          资源分配
        </Button>,
        <Button
          type="link"
          onClick={() => {
            setShowRoleModal(true);
            setRoleFormValues(record);
          }}
        >
          编辑
        </Button>,
        <Popconfirm
          title="确认删除吗？"
          okText="确定"
          cancelText="取消"
          onConfirm={() => delRole(record.id)}
        >
          <Button
            // className={styles.removeBtn}
            size="small"
            type="link"
            danger
          >
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  //查询列表，可通过菜单名称查询
  const getRoleList = async ({
    pageNo,
    pageSize,
    keyword,
  }: {
    pageNo?: number;
    pageSize?: number;
    keyword?: string;
  }) => {
    setLoading(true);
    const requestParams: GetRoleListRequestParams = {
      pageNo: pageNo,
      pageSize: pageSize,
      keyword: keyword,
      officeId: '',
    };
    // console.log(requestParams);
    const res = await queryRoleList(requestParams);
    if (res.code == 200) {
      setData(res.data);
      // formateList(res.data)
      // @ts-ignore
      // setTotal(res.data.total);
    }
    setLoading(false);
  };

  //根据角色ID，删除角色，调用DeleteRoleRequest接口
  //todo: 删除角色
  const delRole = async (id?: string) => {
    setLoading(true);
    const res = await DeleteRoleRequest({
      ids: id,
    });
    if (res.code == 200) {
      setLoading(false);
      actionRef?.current?.reload();
      message.success('删除成功！');
    } else {
      setLoading(false);
      message.error('删除失败！');
    }
  };
  //添加角色成功触发的函数
  //todo: onSuccess
  const onSuccess = async () => {
    actionRef?.current?.reload();
  };
  const onCancel = () => {
    setShowRoleModal(false);
    setRoleFormValues({});
  };

  // 权限分配取消
  const onCancelPermission = () => {
    setShowRolePermissionModal(false);
    setRoleId('');
  };
  // 选择
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  //分页-点击页码设置页码状态
  //todo: 分页，点击页码触发分页
  // const onPageChange: PaginationProps['onChange'] = page => {
  //   setCurrentPage(page.toString());
  // };

  return (
    <div>
      <Card style={{ marginBottom: '20px' }}>
        <Form layout="inline">
          <Form.Item label="角色名称">
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button type="default" icon={<SyncOutlined />}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Card
        title={
          <Space>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                setShowRoleModal(true);
              }}
            >
              新增
            </Button>
            <Button
              type="primary"
              icon={<DeleteOutlined />}
              danger
              disabled={selectedRowKeys.length === 0}
              onClick={() => {
                delRole(selectedRowKeys.toString());
              }}
            >
              批量删除
            </Button>
          </Space>
        }
      >
        <Table
          style={{ marginBottom: '20px' }}
          columns={columns}
          rowSelection={{
            //  selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
            selectedRowKeys,
            onChange: onSelectChange,
          }}
          dataSource={data}
          loading={loading}
          rowKey="id"
          size="small"
          pagination={false}
        />
        {/* <Pagination showTotal={(total) => `共 ${total} 条数据`} showQuickJumper current={Number(currentPage)||1} pageSize={Number(pageSize) || 5} total={Number(total)||0}  onChange={onPageChange}/> */}
      </Card>
      {(roleFormValues && Object.keys(roleFormValues).length) || showRoleModal ? (
        <RoleFormModal
          roleFormValues={roleFormValues}
          onSuccess={onSuccess}
          show={showRoleModal}
          onCancel={onCancel}
        ></RoleFormModal>
      ) : null}
      {roleId && showRolePermissionModal ? (
        <RolePermissionModal
          roleId={roleId}
          onSuccess={onSuccess}
          show={showRolePermissionModal}
          onCancel={onCancelPermission}
        ></RolePermissionModal>
      ) : null}
    </div>
  );
};
export default RoleList;
